import {defineStore} from 'pinia'
import {Ref, ref,} from "vue";
import {Tab} from "@/store/modules/tabs/type.ts";

export const useTabsStore = defineStore('tabsStore', () => {
        // 定义选项卡数据
        const tabList: Ref<Tab[]> = ref([])

        // 添加选项卡数据
        const addTab = (tab: Tab) => {
            // 检查选项卡是否已经存在选项卡里面
            if (tabList.value.some(item => item.path === tab.path)) return
            if (tab.path === '/dashboard') {
                // 如果是首页，添加到第一个
                tabList.value.unshift(tab)
            } else {
                tabList.value.push(tab)
            }
        }

        // 关闭指定选项卡
        const removeTab = (path: string): void => {
            tabList.value = tabList.value.filter(item => item.path !== path);
        };

        // 关闭其他选项卡(除首页)
        const clearTabs = (): void => {
            tabList.value = tabList.value.filter(item => item.path === '/dashboard');
        };

        // 关闭左侧选项卡
        const closeLeftTabs = (currentPath: string): void => {
            const index = tabList.value.findIndex(item => item.path === currentPath);
            if (index > 1) {
                tabList.value.splice(1, index - 1); // 保留首页
            }
        };

        // 关闭右侧选项卡
        const closeRightTabs = (currentPath: string): void => {
            const index = tabList.value.findIndex(item => item.path === currentPath);
            if (index !== -1) {
                tabList.value.splice(index + 1);
            }
        };


        const clearTab = () => {
            tabList.value = [] // 重置为初始状态
        }


        return {tabList, addTab,clearTabs,removeTab,closeLeftTabs,closeRightTabs,clearTab}
    },
    {
        persist: true, // 持久化整个 store
    },
)
